<template>
  <div>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="选择课程" prop="parentName">
       <el-popover
          ref="courseListPopover"
          placement="bottom-start"
          v-model="popoverVisible"
          trigger="click">
          <el-tree
            :data="courseList"
            :props="courseTreeProps"
            node-key="courseId"
            ref="courseListTree"
            @current-change="courseTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:courseListPopover :readonly="true" placeholder="点击选择上级菜单"
          class="menu-list__input"></el-input>
      </el-form-item>
        <el-form-item label="类型" prop="contentTitle">
        <el-select v-model="value" placeholder="请选择">
          <el-option label="类型1" value="0"></el-option>
          <el-option label="类型2" value="1"></el-option>
        </el-select>  
      </el-form-item>          
      <el-form-item label="内容标题" prop="contentTitle">
        <el-input v-model="dataForm.contentTitle" placeholder="内容标题"></el-input>
      </el-form-item>
      <el-form-item label="缩略图 " prop="imgUrl">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="动画导入" prop="contentResourse">
        <el-upload
          class="upload-demo"
          :action="url"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          multiple
          :limit="1"
          :on-success="videoUploadSuccess"
          :before-upload="beforeDhdrUpload"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="内容序号" prop="contentNo">
        <el-input v-model="dataForm.contentNo" placeholder="第N课"></el-input>
      </el-form-item>
      <!-- 要点讲解 -->
      <el-form-item label="要点讲解">
        <el-table fixed="center" border :data="gist" style="width: 100%">
          <el-table-column  prop="img" label="图片" >
          </el-table-column>
          <el-table-column  prop="audio"  label="音频" >
          </el-table-column>
          <el-table-column  fixed="right" header-align="center" align="center" width="150"  label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle('gist',scope)">修改</el-button>
              <el-button type="text" size="small" @click="removeRow('gist',scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateHandle('gist')">新增</el-button>
      </el-form-item>
      <!-- 动态演示 -->
      <el-form-item label="动态演示">
        <el-table fixed="center" border :data="videoUrle" style="width: 100%">
          <el-table-column  prop="vedio" label="视频" >
          </el-table-column>
          <el-table-column  prop="img"  label="图片" >
          </el-table-column>
          <el-table-column  fixed="right" header-align="center" align="center" width="150"  label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle1(scope)">修改</el-button>
              <el-button type="text" size="small" @click="removeRow('videoUrle',scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateHandle1()">新增</el-button>
      </el-form-item>
      <!-- 知识宝盒 -->
      <el-form-item label="知识宝盒">
        <el-table fixed="center" border :data="summarize" style="width: 100%">
          <el-table-column  prop="img" label="图片">
          </el-table-column>
          <el-table-column  prop="audio"  label="音频">
          </el-table-column>
          <el-table-column  fixed="right" header-align="center" align="center" width="150"  label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle('summarize',scope)">修改</el-button>
              <el-button type="text" size="small" @click="removeRow('summarize',scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateHandle('summarize')">新增</el-button>
      </el-form-item>
      <!-- 知识竞答 -->
      <el-form-item label="知识竞答">
        <el-table fixed="center" border :data="exercises" style="width: 100%">
          <el-table-column  prop="title" label="题目">
          </el-table-column>
          <el-table-column  fixed="right" header-align="center" align="center" width="150"  label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle2(scope)">修改</el-button>
              <el-button type="text" size="small" @click="removeRow('exercises',scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateHandle2()">新增</el-button>
      </el-form-item>
      <el-form-item class="save">
        <el-button type="primary" @click="dataFormSubmit()">保存</el-button>
      </el-form-item>
    </el-form>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="refreshDataList"></add-or-update>
    <add-or-update1 v-if="addOrUpdateVisible1" ref="addOrUpdate1" @refreshDataList="addVideoUrle"></add-or-update1>
    <add-or-update2 v-if="addOrUpdateVisible2" ref="addOrUpdate2" @refreshDataList="addExercises"></add-or-update2>
  </div>
</template>

<script>
  import {treeDataTranslate} from '@/utils'
  import AddOrUpdate from './coursecontent-open'
  import AddOrUpdate1 from './coursecontent-open1'
  import AddOrUpdate2 from './coursecontent-open-zsjd'
  export default {
    data () {
      return {
        popoverVisible: false,

        addOrUpdateVisible: false,
        rowIndex:0,

        addOrUpdateVisible1: false,
        videoUrle: [],
        rowIndex1:0,

        summarize: [],
        type: '', //记录修改的课程内容的类型

        //知识竞答
        addOrUpdateVisible2: false,
        exercises: [],
        rowIndex2:0,

        dialogTableVisible:true,
        gist:[],
        visible: false,
        innerVisible: false,
        url: '',
        imageUrl: '',
        limit: 1,
        fileList: [],
        fileListUrls: [],
        courseList: [],
        courseTreeProps: {
          label: 'courseTitle',
          children: 'children'
        },
        dataForm: {
          courseContentId: 0,
          contentTitle: '',
          imgUrl: '',
          courseId: '',
          contentResourse: '',
          contentNo: '',
          parentName: '',
          courseDemoEntity: {}
        },
        courseDemoEntity: {
          accessory:"string",
          contentId :0,
          courseDemoId :0,
          exercises : "string",
          gist : "string",
          summarize : "string",
          videoUrle : "string"
        },
        dataRule: {
          contentTitle: [
            { required: true, message: '内容标题不能为空', trigger: 'blur' }
          ],
          courseId: [
            { required: true, message: '课程id不能为空', trigger: 'blur' }
          ],
          contentResourse: [
            { required: true, message: '资源地址不能为空', trigger: 'blur' }
          ],
          contentNo: [
            { required: true, message: '内容序号不能为空', trigger: 'blur' }
          ],
          parentName: [
            {required: true, message: '上级菜单不能为空', trigger: 'change'}
          ],
        }
      }
    },
    components: {
      AddOrUpdate,
      AddOrUpdate1,
      AddOrUpdate2
    },
    activated() {
      this.init(this.$route.query.id)
    },
    methods: {
      // 新增 / 修改 要点讲解
      addOrUpdateHandle (type, scope) {
        this.type = type
        if(scope) this.rowIndex = scope.$index
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(scope ? scope.row : undefined)
        })
      },
      // 新增 / 修改 动态演示
      addOrUpdateHandle1 (scope) {
        if(scope) this.rowIndex1 = scope.$index
        this.addOrUpdateVisible1 = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate1.init(scope?scope.row:undefined)
        })
      },
      // 新增 / 修改 知识竞答
      addOrUpdateHandle2(scope) {
        if(scope) this.rowIndex2 = scope.$index
        this.addOrUpdateVisible2 = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate2.init(scope?scope.row:undefined)
        })
      },
      //判断是否为JSON格式
      isJSON(str) {
        if (typeof str == 'string') {
          try {
              var obj=JSON.parse(str);
              if(typeof obj == 'object' && obj ){
                return true;
              }else{
                return false;
              }
          } catch(e) {
            return false;
          }
        }
      },

      init (id) {
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)

        this.imageUrl=''
        this.fileList = []
        this.gist = []
        this.videoUrle = []
        this.summarize = []
        this.exercises = []

        this.$http({
          url: this.$http.adornUrl('/admin/course/list'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          data.list.push({
            courseId: 0,
            courseTitle: '一级菜单',
            fId: -1
          })
          this.courseList = treeDataTranslate(data.list, 'courseId', 'fId')
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        })

        this.dataForm.courseContentId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.courseContentId) {
            this.$http({
              url: this.$http.adornUrl(`/admin/coursecontent/info/${this.dataForm.courseContentId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                //console.log(data)

                this.dataForm.contentTitle = data.courseContent.contentTitle
                this.dataForm.courseId = data.courseContent.courseId
                this.dataForm.contentResourse = data.courseContent.contentResourse
                this.dataForm.contentNo = data.courseContent.contentNo
                this.dataForm.imgUrl = data.courseContent.imgUrl
                this.imageUrl= data.courseContent.imgUrl
                this.courseListTreeSetCurrentNode()
                // data.courseContent.contentResourse
                let localGist = data.courseContent.courseDemoEntity.gist
                if(this.isJSON(localGist)) this.gist = JSON.parse(data.courseContent.courseDemoEntity.gist)
                let localVideoUrle = data.courseContent.courseDemoEntity.videoUrle
                if(this.isJSON(localVideoUrle)) this.videoUrle = JSON.parse(data.courseContent.courseDemoEntity.videoUrle)
                let localSummarize = data.courseContent.courseDemoEntity.summarize
                if(this.isJSON(localSummarize)) this.summarize = JSON.parse(data.courseContent.courseDemoEntity.summarize)
                let localExercises = data.courseContent.courseDemoEntity.exercises
                if(this.isJSON(localExercises)) this.exercises = JSON.parse(data.courseContent.courseDemoEntity.exercises)
                if(this.fileList.length!=1){
                  let nameList = data.courseContent.contentResourse.split('/');
                  let name = nameList[nameList.length-1]
                  this.fileList.push({name,url: data.courseContent.contentResourse});
                }
                
                this.dataForm.courseDemoEntity.gist = data.courseContent.courseDemoEntity.gist
                this.dataForm.courseDemoEntity.videoUrle = data.courseContent.courseDemoEntity.videoUrle
                this.dataForm.courseDemoEntity.summarize = data.courseContent.courseDemoEntity.summarize
                this.dataForm.courseDemoEntity.exercises = data.courseContent.courseDemoEntity.exercises
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/admin/coursecontent/${!this.dataForm.courseContentId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                ...this.dataForm
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                    this.$emit('addVideoUrle')
                    this.$emit('addExercises')
                  }
                })
                this.$router.push({path: '/web-coursecontent'})
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      handleAvatarSuccess (res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        if (res && res.code === 0) {
          if (this.num === this.successNum) {
            this.$message.success('上传成功')
            this.dataForm.imgUrl = res.url
          }
        } else {
          this.$message.error(res.msg)
        }
      },
      beforeDhdrUpload(file) {
        if (file.type !== 'video/mp4') {
          this.$message.error('只支持mp4格式的视频上传！')
          return false
        }
      },
      beforeAvatarUpload(file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
      },
      handleRemove (file, fileList) {
        console.log(file, fileList)
      },
      handlePreview (file) {
        console.log(file)
      },
      handleExceed (files, fileList) {
        this.$message.warning(`最多上传一个视频`)
      },
      videoUploadSuccess (response, file, fileList){
        //debugger;
        if (response.code === 0) {
          // this.fileList.push(response.url);
          this.dataForm.contentResourse=response.url
        }
      },
       // 菜单树选中
      courseTreeCurrentChangeHandle(data, node) {
        if (data._level !== 4) {
          this.$message.warning('请选择对应目录')
          return false
        }
        this.dataForm.courseId = data.courseId
        this.dataForm.parentName = data.courseTitle
        this.popoverVisible = !this.popoverVisible
      },
       // 菜单树设置当前选中节点
      courseListTreeSetCurrentNode() {
        this.$refs.courseListTree.setCurrentKey(this.dataForm.courseId)
        this.dataForm.parentName = (this.$refs.courseListTree.getCurrentNode() || {})['courseTitle']
      },
      removeRow(type, row){
        this.$confirm('确认删除该条数据？?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this[type].splice(row.$index, 1)
          let arr = JSON.parse(this.dataForm.courseDemoEntity[type])
          arr.splice(row.$index, 1)
          if (arr.length !== 0 ) {
            this.dataForm.courseDemoEntity[type] = JSON.stringify(arr)
          }else {
            this.dataForm.courseDemoEntity[type] = 'string'
          }
        })
      },
      refreshDataList(data,isUpdata){
        if(this.type === 'summarize') {
          if(!isUpdata) {
            this.summarize.push(data)
          }else {
            this.summarize.splice(this.rowIndex, 1, data)
          }
        }else {
          if(!isUpdata) {
            this.gist.push(data)
          }else {
            this.gist.splice(this.rowIndex, 1, data)
          }
        }
        this.courseDemoEntity.summarize = JSON.stringify(this.summarize)
        this.courseDemoEntity.gist = JSON.stringify(this.gist)
        this.dataForm.courseDemoEntity.summarize = this.courseDemoEntity.summarize
        this.dataForm.courseDemoEntity.gist = this.courseDemoEntity.gist
      },
      addVideoUrle(data,isUpdata) {
        if(!isUpdata) {
          this.videoUrle.push(data)
        }else {
          this.videoUrle.splice(this.rowIndex1, 1, data)
        }
        this.courseDemoEntity.videoUrle = JSON.stringify(this.videoUrle)
        this.dataForm.courseDemoEntity.videoUrle = this.courseDemoEntity.videoUrle
      },
      addExercises(data,isUpdata) {
        if(!isUpdata) {
          this.exercises.push(data)
        }else {
          this.exercises.splice(this.rowIndex2, 1, data)
        }
        this.courseDemoEntity.exercises = JSON.stringify(this.exercises)
        this.dataForm.courseDemoEntity.exercises = this.courseDemoEntity.exercises
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .save .el-form-item__content {
    margin: 0;
    text-align: center;
  }
</style>